/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.solestac.view;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.colswe.solestac.VO.RequestVO;
import org.colswe.solestac.VO.StudentVO;
import org.colswe.solestac.control.RequestControl;
import org.colswe.solestac.control.StudentControl;

/**
 *
 * @author solid
 */
public class NewRequest extends javax.swing.JPanel {

    /**
     * Creates new form Request
     */
    private StudentControl studentControl;
    private RequestControl requestControl;
    private StudentVO student;
    private Principal parent;

    public NewRequest(Principal parent) {
        requestControl = new RequestControl();
        studentControl = new StudentControl();
        initComponents();
        this.parent = parent;
    }

    public void  setStudent(StudentVO student){
        this.student = student;
    }
    public StudentVO getStudent(){
        return this.student;
    }
    
    private void cleanTF(){
        namesLbl.setText("Nombres");
        lastNamesLbl.setText("Apellidos");
        documentLbl.setText("Cédula");
        codeLbl.setText("Código");
        programLbl.setText("Programa curricular");
    }
    public void setInfo(){
        namesLbl.setText(namesLbl.getText()+ ": " + student.getName());
        lastNamesLbl.setText(lastNamesLbl.getText()+ ": " +student.getLastName());
        documentLbl.setText(documentLbl.getText()+ ": " +student.getDocument());
        codeLbl.setText(codeLbl.getText()+ ": " +student.getCode());
        programLbl.setText(programLbl.getText()+ ": " +student.getProgram());
        
        setTable();
        
    }
    
    public Principal getPrincipal(){
        return parent;
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tableTitleLbl = new javax.swing.JLabel();
        programLbl = new javax.swing.JLabel();
        documentLbl = new javax.swing.JLabel();
        nextButton = new javax.swing.JButton();
        codeLbl = new javax.swing.JLabel();
        lblStudent = new javax.swing.JLabel();
        studentTF = new javax.swing.JTextField();
        studentSearchButton = new javax.swing.JButton();
        namesLbl = new javax.swing.JLabel();
        lastNamesLbl = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        requestTable = new javax.swing.JTable();

        setBackground(new java.awt.Color(255, 255, 255));

        tableTitleLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        tableTitleLbl.setText("Solicitudes del Estudiante");

        programLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        programLbl.setText("Programa Curricular");

        documentLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        documentLbl.setText("Cédula");

        nextButton.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        nextButton.setText("Siguiente");
        nextButton.setEnabled(false);
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        codeLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        codeLbl.setText("Código");

        lblStudent.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        lblStudent.setText("Estudiante");

        studentTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                studentTFActionPerformed(evt);
            }
        });

        studentSearchButton.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        studentSearchButton.setText("Buscar");
        studentSearchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                studentSearchButtonActionPerformed(evt);
            }
        });

        namesLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        namesLbl.setText("Nombres");

        lastNamesLbl.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16)); // NOI18N
        lastNamesLbl.setText("Apellidos");

        requestTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Tipo", "Fecha", "Periodo", "Instancia Actual"
            }
        ));
        jScrollPane2.setViewportView(requestTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(codeLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lastNamesLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(tableTitleLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 630, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblStudent)
                                .addGap(18, 18, 18)
                                .addComponent(studentTF, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(documentLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(programLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(studentSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(namesLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 416, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(47, 47, 47)
                                .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 69, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStudent, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(studentTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(studentSearchButton)
                    .addComponent(nextButton))
                .addGap(52, 52, 52)
                .addComponent(namesLbl)
                .addGap(18, 18, 18)
                .addComponent(lastNamesLbl)
                .addGap(28, 28, 28)
                .addComponent(documentLbl)
                .addGap(18, 18, 18)
                .addComponent(codeLbl)
                .addGap(33, 33, 33)
                .addComponent(programLbl)
                .addGap(47, 47, 47)
                .addComponent(tableTitleLbl)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(149, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        parent.requestForm(student);        
    }//GEN-LAST:event_nextButtonActionPerformed

    private void studentTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_studentTFActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_studentTFActionPerformed
    
    
    private String getDateTime(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        return dateFormat.format(date);
    }
    
    
    private void setTable(){
        List<RequestVO> requests = requestControl.searchByStudent(student.getDocument());
        if(requests != null && !requests.isEmpty()){
           int rows = requests.size();           
           Object[][] tableModel = new Object[rows][5];
           for (int i = 0; i < rows; i++){
               System.out.println("i: "+i);
               
               tableModel[i][0] = requests.get(i).getId();
               tableModel[i][1] = requests.get(i).getRequestType();
               tableModel[i][2] = requests.get(i).getDate();
               tableModel[i][3] = requests.get(i).getAcademicPeriod();
               tableModel[i][4] = requests.get(i).getInstance();               
           }        
                   
           requestTable.setModel(new DefaultTableModel(tableModel,new String[]{"id","Tipo","Fecha","Periodo","Instancia Actual"}));
           
        }
    }
    
    
    
    private void studentSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_studentSearchButtonActionPerformed
        
        String document = studentTF.getText();
        int docValidation = studentControl.validateDocument(document);
       
        if (docValidation == 0) {
            
            List<StudentVO> students = studentControl.searchStudentByDocument(document);
            
            if(students != null && !students.isEmpty()){
                student = students.get(0);
                
            }
            else{
                student = null;
            }
            if(student != null){
                
                nextButton.setEnabled(true);      
                cleanTF();
                setInfo();
            }
            else{
               parent.setEnabled(false);
                NewStudent newStudent = new NewStudent(this,document);
                newStudent.addWindowListener(new WindowListener() {

                    @Override
                    public void windowOpened(WindowEvent we) {
                       
                    }

                    @Override
                    public void windowClosing(WindowEvent we) {
                       
                    }

                    @Override
                    public void windowClosed(WindowEvent we) {
                      parent.setEnabled(true);
                      if(student != null){
                          setInfo();
                      }
                    }

                    @Override
                    public void windowIconified(WindowEvent we) {
                        
                    }

                    @Override
                    public void windowDeiconified(WindowEvent we) {
                       
                    }

                    @Override
                    public void windowActivated(WindowEvent we) {
                        
                    }

                    @Override
                    public void windowDeactivated(WindowEvent we) {
                        
                    }
                });
            }
            
        } else if (docValidation == -1) {
            JOptionPane.showMessageDialog(this, "El valor ingresado no es numérico",
                    "Cédula inválida",JOptionPane.INFORMATION_MESSAGE);            
        } else if(docValidation == -2){
            JOptionPane.showMessageDialog(this, "El valor ingresado no está entre el rango de límites;"
                    + "La cédula debe contener entre 6 y 12 dígitos", "Cédula inválida",JOptionPane.INFORMATION_MESSAGE);
        }else if(docValidation == -3){
            JOptionPane.showMessageDialog(this, "Ocurrió una exepción mientras se realizaba la operación",
                    "Error inesperado",JOptionPane.ERROR_MESSAGE);
        }
     
        
    }//GEN-LAST:event_studentSearchButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel codeLbl;
    private javax.swing.JLabel documentLbl;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lastNamesLbl;
    private javax.swing.JLabel lblStudent;
    private javax.swing.JLabel namesLbl;
    private javax.swing.JButton nextButton;
    private javax.swing.JLabel programLbl;
    private javax.swing.JTable requestTable;
    private javax.swing.JButton studentSearchButton;
    private javax.swing.JTextField studentTF;
    private javax.swing.JLabel tableTitleLbl;
    // End of variables declaration//GEN-END:variables
}
